﻿# -*- encoding: utf-8 -*-

from verta.libs.default.views import DefaultView
from verta.bookmark.models import URL, Bookmark, Kind, Tag

class Crud(DefaultView):
    def put_tag(self, bookmark, tags):
        '''Returns a tag for query name. If it does not exist, it will be created and returned'''
        if isinstance(tags, str):
            # Replace commas by space, because tags are separated by spaces
            tags = tags.replace(',', ' ')
            # Get list of tags, spliting string by spaces
            tags = tags.split(' ')
        # For each tag
        for name in tags:
            # Generate tag alias
            alias = self.treat(name)
            # Verify if it exists
            try:
                tag = Tag.objects.get(alias=alias)
            # If it does not exist, create it
            except Tag.DoesNotExist:
                tag = Tag(name=name, alias=alias)
                tag.save()
            # Insert bookmark
            tag.bookmark.add(bookmark)
        
    def create(self):
        '''Create a Bookmark'''
        # Required parameters and fields required to add a bookmark
        required_fields = ['title', 'public', 'url', 'kind', 'user', 'tag']
        # List of missing parameters
        missing = []
        # Verify each required field
        for required in required_fields:
            if not required in self.method:
                missing.append(required)
        # If there are parameters missing, show error message        
        if missing:
            return self.error_message(fields=missing)
        #
        # TODO: Treat content before insert
        #
        self.params = {}
        for field in self.method:
            self.params[field] = self.treat(self.method[field])
        
        # Get parameter to treat
        tags = self.method['tags']
        # Returns description if it has a value else return an empty string
        description = ('description' in self.method) and self.method['description'] or ''
        # Try to set public parameter as boolean
        public = self.method['public'].lower()
        
        if public == 'true':
            public = True
        elif public == 'false':
            public = False
        else:
            # If it isn't boolean, send error message
            return self.error_message(fields=['public'])
        
        # Get kind of bookmark
        try:
            kind = Kind.objects.get(name=self.method['kind'])
        except Kind.DoesNotExist:
            return self.error_message(fields=['kind'])
        
        self.method = self.params
        # Get or save URL required
        try:
            url = URL.objects.get(name=self.method['url'])
        except URL.DoesNotExist:
            url = URL(name=self.method['url'])
            url.save()
        
        #
        # Save bookmark info
        #
        
        bookmark = Bookmark(
                        title=self.method['title'], 
                        description=description,
                        public = public,
                        url = url,
                        kind = kind,
                        user = self.user
                    )
        bookmark.save()
        # Insert tags into bookmark
        self.put_tags(bookmark, tags)
        
        return self.success_message('create')
